package com.taotao.sso.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.utils.CookieUtils;
import com.taotao.sso.pojo.User;
import com.taotao.sso.service.UserService;


@Controller
public class UserController {
	@Autowired
	private UserService userService;
	
	private static final String COOKIES_NAME="TT_TOKEN";

	/**
	 * 跳转注册页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/user/{page}", method = RequestMethod.GET)
	public String toRegister(@PathVariable(value="page") String page) {

		return page;

	}

	/**
	 * 检测数据是否可用
	 * 
	 * @param param
	 * @param type
	 * @return
	 */
	@RequestMapping("/user/{param}/{type}")
	public ResponseEntity<Boolean> check(
			@PathVariable(value = "param") String param,
			@PathVariable(value = "type") Integer type) {
		try {
			Boolean boo = this.userService.check(param, type);
			if (boo == null) {
				// 400
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
			}
			// 200返回获取的值给页面 为了兼容前台数据取反
			return ResponseEntity.ok(!boo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 异常500
		return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
	}

	// $.ajax({
	// type : "POST",
	// url : "/service/user/doRegister",
	// result.status == "200"
	/**
	 * 注册用户
	 * 
	 * @return
	 */
	@RequestMapping(value="/user/doRegister",method=RequestMethod.POST)
	public ResponseEntity<Map<String, Object>> saveUser(@Valid User user,BindingResult bindingResult) {
		try {
			Map<String, Object> result = new HashMap<String, Object>();
			if (bindingResult.hasErrors()) {
				//校验有误
				List<String> msgs = new ArrayList<String>();
				List<ObjectError> errors = bindingResult.getAllErrors();
				for (ObjectError error : errors) {
					msgs.add(error.getDefaultMessage());
					}
				result.put("status", "400");
				result.put("data", StringUtils.join(msgs, ','));
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result); 
			}
			Boolean boo = this.userService.saveUser(user);
			if (boo) {
				// 注册成功
				result.put("status", "200");
			} else {
				// 注册失败
				result.put("status", "300"); 
				// 欢迎下次注册
				result.put("data", "请从新注册!");
			}
			return ResponseEntity.ok(result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//500异常
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
	}
	/*
	 * type: "POST",
            url: "/service/user/doLogin?r=" + Math.random(),
	 * 
	 */
	/**
	 * 登录
	 * @param password
	 * @param username
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/user/doLogin",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> doLogin(
			@RequestParam("username") String username,
			@RequestParam("password")String password,
			HttpServletRequest request,
			HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			
			String token = this.userService.doLogin(username,password);
			if (null==token) {
				//登录失败
				result.put("status", 400);
			}else{
				//登录成功
				result.put("status", 200);
				//获得token放到cookie中
				CookieUtils.setCookie(request, response, COOKIES_NAME, token);
			}
					
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.put("status", 500);
		}
		return result;
	}
	
	@RequestMapping(value="/user/query/{token}",method=RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<User> getCookieUser(@PathVariable("token")String token){
			try {
				User user = this.userService.getCookie(token);
				if(user!=null){
					return ResponseEntity.ok(user);
				}
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
	}
}
